package com.xjrsoft.module.customer.erp_model.eRP_PurchaseReturnInfo.service.impl;
import cn.hutool.db.Db;
import cn.hutool.db.Entity;
import com.baomidou.dynamic.datasource.annotation.DS;
import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.xjrsoft.common.dbmodel.utils.DataSourceUtil;
import com.xjrsoft.core.tool.utils.StringUtil;
import com.xjrsoft.module.customer.erp_model.eRP_PurchaseReceiptInfo.entity.ErpPurchasereceiptentry;
import com.xjrsoft.module.customer.erp_model.eRP_PurchaseReceiptInfo.service.IErpPurchasereceiptrentryService;
import com.xjrsoft.module.customer.erp_model.eRP_PurchaseReceiptInfo.service.impl.ErpPurchasereceiptServiceImpl;
import com.xjrsoft.module.customer.erp_model.eRP_PurchaseReturnInfo.dto.ErpPurchasereturnDto;
import com.xjrsoft.module.customer.erp_model.eRP_PurchaseReturnInfo.dto.ErpPurchasereturnentryDto;
import com.xjrsoft.module.customer.erp_model.eRP_PurchaseReturnInfo.entity.ErpPurchasereturn;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.xjrsoft.module.customer.erp_model.eRP_PurchaseReturnInfo.entity.ErpPurchasereturnentry;
import com.xjrsoft.module.customer.erp_model.eRP_PurchaseReturnInfo.mapper.ErpPurchasereturnentryMapper;
import com.xjrsoft.module.customer.erp_model.eRP_PurchaseReturnInfo.dto.ErpPurchasereturnListDto;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.xjrsoft.common.page.ConventPage;

import java.math.BigDecimal;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import com.xjrsoft.module.customer.erp_model.eRP_PurchaseReturnInfo.mapper.ErpPurchasereturnMapper;
import com.xjrsoft.module.customer.erp_model.eRP_PurchaseReturnInfo.service.IErpPurchasereturnService;
import com.xjrsoft.core.mp.base.BaseService;
import com.xjrsoft.module.customer.erp_model.eRP_PurchaseReturnInfo.vo.ErpPurchasereturnentryVo;
import com.xjrsoft.module.customer.erp_model.erpPurchaseOrderInfo.entity.ErpPurchaseorder;
import com.xjrsoft.module.customer.erp_model.erpPurchaseOrderInfo.entity.ErpPurchaseorderentry;
import com.xjrsoft.module.customer.erp_model.erpPurchaseOrderInfo.service.IErpPurchaseorderService;
import com.xjrsoft.module.customer.erp_model.erpPurchaseOrderInfo.service.IErpPurchaseorderentryService;
import com.xjrsoft.module.customer.erp_model.erp_inventoryManage.entity.ErpInventory;
import com.xjrsoft.module.customer.erp_model.erp_inventoryManage.service.IErpInventoryService;
import lombok.AllArgsConstructor;
import lombok.SneakyThrows;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 *  服务实现类
 *
 * @author pp
 * @since 2021-09-24
 */
@Service
@AllArgsConstructor
//@DS("86cb2f711211a7d00cdb12c5a265c4a8")
public class ErpPurchasereturnServiceImpl extends BaseService<ErpPurchasereturnMapper, ErpPurchasereturn> implements IErpPurchasereturnService {

	private ErpPurchasereturnentryMapper erpPurchasereturnentryMapper;

	private IErpPurchaseorderentryService erpPurchaseorderentryService;

	private IErpPurchasereceiptrentryService erpPurchasereceiptentryService;

	//使用其他service类的时候要注入
	@Autowired
	private final IErpInventoryService erpInventoryService;

	@Autowired
	private final IErpPurchaseorderService erpPurchaseorderService;

	@Override
	public IPage<ErpPurchasereturn> getPageList(ErpPurchasereturnListDto pageListDto) {
		Wrapper<ErpPurchasereturn> wrapper = Wrappers.<ErpPurchasereturn>query().lambda()				.eq(!StringUtil.isEmpty(pageListDto.getF_ReturnNumber()), ErpPurchasereturn::getFReturnnumber, pageListDto.getF_ReturnNumber())
				.ge(!StringUtil.isEmpty(pageListDto.getF_ReturnDate_Start()), ErpPurchasereturn::getFReturndate, pageListDto.getF_ReturnDate_Start())
				.le(!StringUtil.isEmpty(pageListDto.getF_ReturnDate_End()), ErpPurchasereturn::getFReturndate, pageListDto.getF_ReturnDate_End())
				.like(!StringUtil.isEmpty(pageListDto.getF_ChargePeople()), ErpPurchasereturn::getFChargepeople, pageListDto.getF_ChargePeople())
				.eq(!StringUtil.isEmpty(pageListDto.getF_PurReceiptNumber()), ErpPurchasereturn::getFPurreceiptnumber, pageListDto.getF_PurReceiptNumber())
				.like(!StringUtil.isEmpty(pageListDto.getF_DeliveryUnit()), ErpPurchasereturn::getFDeliveryunit, pageListDto.getF_DeliveryUnit())
				.like(!StringUtil.isEmpty(pageListDto.getF_AuditMark()), ErpPurchasereturn::getFAuditmark, pageListDto.getF_AuditMark())
				.like(!StringUtil.isEmpty(pageListDto.getF_InvalidMark()), ErpPurchasereturn::getFInvalidmark, pageListDto.getF_InvalidMark());
		return this.page(ConventPage.getPage(pageListDto), wrapper);
	}

	@Override
	public String addErpPurchasereturn(ErpPurchasereturnDto erpPurchasereturnDto,ErpPurchasereturn erpPurchasereturn, List<ErpPurchasereturnentryDto> erpPurchasereturnentryDtos, List<ErpPurchasereturnentry> erpPurchasereturnentryList) throws SQLException {
		String erpPurchasereturnId = IdWorker.get32UUID();
		updateInfo(erpPurchasereturnDto,erpPurchasereturnentryDtos);

		erpPurchasereturn.setFId(erpPurchasereturnId);

		boolean isSuccess = this.save(erpPurchasereturn);
		erpPurchasereturnentryList.forEach(erpPurchasereturnentry -> {erpPurchasereturnentry.setFReturnid(erpPurchasereturn.getFId());
			erpPurchasereturnentry.setFPurreceptid(erpPurchasereturnDto.getFPurreceiptid());});
		this.saveBatch(erpPurchasereturnentryList, ErpPurchasereturnentry.class, ErpPurchasereturnentryMapper.class);


		return isSuccess ? erpPurchasereturnId : null;
	}



	@SneakyThrows
	@Override
	public boolean updateErpPurchasereturn(String id,ErpPurchasereturnDto erpPurchasereturnDto, List<ErpPurchasereturnentryDto> erpPurchasereturnentryDtos,ErpPurchasereturn erpPurchasereturn, List<ErpPurchasereturnentry> erpPurchasereturnentryList)  {
		if (updateInfo(erpPurchasereturnDto,erpPurchasereturnentryDtos)){
			erpPurchasereturn.setFId(id);
			erpPurchasereturnentryList.forEach(erpPurchasereturnentry -> {erpPurchasereturnentry.setFReturnid(id);
				erpPurchasereturnentry.setFPurreceptid(erpPurchasereturnDto.getFPurreceiptid());});
			erpPurchasereturnentryMapper.delete(Wrappers.<ErpPurchasereturnentry>query().lambda().eq(ErpPurchasereturnentry::getFReturnid, id));
			this.saveBatch(erpPurchasereturnentryList, ErpPurchasereturnentry.class, ErpPurchasereturnentryMapper.class);
			return this.updateById(erpPurchasereturn);
		}
		return false;
	}
	public  boolean updateInfo(ErpPurchasereturnDto erpPurchasereturnDto, List<ErpPurchasereturnentryDto> erpPurchasereturnentryDtos) throws SQLException {
		List<ErpPurchaseorderentry> erpPurchaseorderentryList=new ArrayList<ErpPurchaseorderentry>();
		ErpPurchaseorder erpPurchaseorder=new ErpPurchaseorder();
		Integer status=erpPurchasereturnDto.getFStatus();
		List<Integer> statusList=new ArrayList<Integer>();
		for (int i=0;i<erpPurchasereturnentryDtos.size();i++)
		{
			ErpPurchaseorderentry erpPurchaseorderentry=new ErpPurchaseorderentry();
			//入库单位和基本单位和库存显示单位都一样可以直接做操作  1.对库存做操作（新增或修改）
			if(erpPurchasereturnentryDtos.get(i).getFBasicunit().equals(erpPurchasereturnentryDtos.get(i).getFUnit())&&erpPurchasereturnentryDtos.get(i).getFComunit().equals(erpPurchasereturnentryDtos.get(i).getFUnit()))
			{
				//根据商品id和仓库id查询是否有此商品的库存数据
				String sql1="SELECT * FROM erp_inventory i where i.F_WarehouseId='"+erpPurchasereturnDto.getFWerahourseid()+ "' and i.F_GoodsId='"+erpPurchasereturnentryDtos.get(i).getFGoodsid()+"'";
				List<Entity> isInventory1= Db.use(DataSourceUtil.getDataSource()).query(sql1);
				ErpInventory erpInventory1=new ErpInventory();
				//如果有的话就修改对应商品的库存
				if (isInventory1.size()>0)
				{
					//修改数量=原有的数据-本次退货的数量
					BigDecimal aftBasicQua= isInventory1.get(0).getBigDecimal("f_basicamount");
					BigDecimal aftComamQua=isInventory1.get(0).getBigDecimal("f_comamount");
					BigDecimal retrurnQua=new BigDecimal(erpPurchasereturnentryDtos.get(i).getFReturnquantity());
					erpInventory1.setFId(isInventory1.get(0).get("f_id").toString());//根据id修改 一定呀加这句
					erpInventory1.setFGoodsid(erpPurchasereturnentryDtos.get(i).getFGoodsid());
					erpInventory1.setFWarehouseid(erpPurchasereturnDto.getFWerahourseid());
					erpInventory1.setFBasicamount(aftBasicQua.subtract(retrurnQua));
					erpInventory1.setFComamount(aftComamQua.subtract(retrurnQua));
					//怎么在一个serveimp里去调用另外一个里面的方法 一定要注入
					erpInventoryService.updateById(erpInventory1);
					erpPurchaseorderentry.setFOrderid(erpPurchasereturnDto.getFPurorderid());//getFPurorderid的值和getFOrderentrtyid的值应该是一样的
					erpPurchaseorderentry.setFGoodsid(erpPurchasereturnentryDtos.get(i).getFGoodsid());
					erpPurchaseorderentry.setFId(erpPurchasereturnentryDtos.get(i).getFOrderentrtyid());
					//未入库数量=旧的未入库数量+退货数量
					erpPurchaseorderentry.setFNoReceiptQua(new BigDecimal(erpPurchasereturnentryDtos.get(i).getFNoReceiptQua()).add(new BigDecimal(erpPurchasereturnentryDtos.get(i).getFReturnquantity())).intValue());
					//已入库数量=旧的已入库数量-退货数量
					erpPurchaseorderentry.setFReceiptQua(new BigDecimal(erpPurchasereturnentryDtos.get(i).getFReceiptQua()).subtract(new BigDecimal(erpPurchasereturnentryDtos.get(i).getFReturnquantity())).intValue());
					erpPurchaseorderentryList.add(erpPurchaseorderentry);
					if(erpPurchaseorderentry.getFReceiptQua()==0)
					{
						statusList.add(status);
					}
				}
				else{
					return  false;
				}
			}
			//不一样先查询换算率得到之后转换
			else {
				//这里组合有四种情况  只有同时满足不相等的情况 才需要同时转换
				//基本单位转换率
				BigDecimal baseConverRate = null;
				//显示单位转换率
				BigDecimal comConverRate=null;
				if(!erpPurchasereturnentryDtos.get(i).getFBasicunit().equals(erpPurchasereturnentryDtos.get(i).getFUnit()) &&!erpPurchasereturnentryDtos.get(i).getFComunit().equals(erpPurchasereturnentryDtos.get(i).getFUnit()))
				{
					//查询转换率
					String sql="select c.F_Id,c.F_ConvertRate,c.F_FullName,c.F_ConvertId,c.F_Description from erp_unitconvertchild c left join erp_unitconvert u on u.F_Id=c.F_ConvertId where c.F_ConvertId='"+erpPurchasereturnentryDtos.get(i).getFUnit()+"'";
					List<Entity>  list= Db.use(DataSourceUtil.getDataSource()).query(sql);

					for (int j=0;j<list.size();j++)
					{
						if (list.get(j).get("f_fullname").toString().equals(erpPurchasereturnentryDtos.get(i).getFComunit().toString()))
						{
							comConverRate=new BigDecimal(list.get(j).get("F_ConvertRate").toString());
						}
						if (list.get(j).get("f_fullname").toString().equals(erpPurchasereturnentryDtos.get(i).getFBasicunit().toString()))
						{
							baseConverRate=new BigDecimal(list.get(j).get("F_ConvertRate").toString());
						}
					}
					//得到转换率之后开始转换
					//根据商品id和仓库id查询是否有此商品的库存数据
					String sql1="SELECT * FROM erp_inventory i where i.F_WarehouseId='"+erpPurchasereturnDto.getFWerahourseid()+ "' and i.F_GoodsId='"+erpPurchasereturnentryDtos.get(i).getFGoodsid()+"'";
					List<Entity> isInventory1=Db.use(DataSourceUtil.getDataSource()).query(sql1);
					ErpInventory erpInventory1=new ErpInventory();
					BigDecimal retrurnQua=new BigDecimal(erpPurchasereturnentryDtos.get(i).getFReturnquantity());
					//如果有的话就修改对应商品的库存
					if (isInventory1.size()>0)
					{
						//修改数量=原有的数据-（本次入库的数量*转换率）
						BigDecimal aftBasicQua= isInventory1.get(0).getBigDecimal("f_basicamount");
						BigDecimal aftComamQua=isInventory1.get(0).getBigDecimal("f_comamount");
						erpInventory1.setFId(isInventory1.get(0).get("f_id").toString());//根据id修改 一定呀加这句
						erpInventory1.setFGoodsid(erpPurchasereturnentryDtos.get(i).getFGoodsid());
						erpInventory1.setFWarehouseid(erpPurchasereturnDto.getFWerahourseid());
						erpInventory1.setFBasicamount(aftBasicQua.subtract(retrurnQua.multiply(baseConverRate)));
						erpInventory1.setFComamount(aftComamQua.subtract(retrurnQua.multiply(comConverRate)));
						erpInventoryService.updateById(erpInventory1);
						erpPurchaseorderentry.setFId(erpPurchasereturnentryDtos.get(i).getFOrderentrtyid());
						erpPurchaseorderentry.setFOrderid(erpPurchasereturnDto.getFPurorderid());
						erpPurchaseorderentry.setFGoodsid(erpPurchasereturnentryDtos.get(i).getFGoodsid());
						//未入库数量=旧的未入库数量+退货数量
						erpPurchaseorderentry.setFNoReceiptQua(new BigDecimal(erpPurchasereturnentryDtos.get(i).getFNoReceiptQua()).add(new BigDecimal(erpPurchasereturnentryDtos.get(i).getFReturnquantity())).intValue());
						//已入库数量=旧的已入库数量-退货数量
						erpPurchaseorderentry.setFReceiptQua(new BigDecimal(erpPurchasereturnentryDtos.get(i).getFReceiptQua()).subtract(new BigDecimal(erpPurchasereturnentryDtos.get(i).getFReturnquantity())).intValue());
						erpPurchaseorderentryList.add(erpPurchaseorderentry);
						if(erpPurchaseorderentry.getFReceiptQua()==0)
						{
							statusList.add(status);
						}
					}
					else{
						return  false;
					}
				}
				else {
					//其中一个需要转换 先判断是基本数量单位需要转换还是库存显示单位需要转换
					//如果库存显示单位和入库单位不相等 就需要转换,否则就是基本单位需要转换
					//先查询出转换率
					String sql="select c.F_Id,c.F_ConvertRate,c.F_FullName,c.F_ConvertId,c.F_Description from erp_unitconvertchild c left join erp_unitconvert u on u.F_Id=c.F_ConvertId where c.F_ConvertId='"+erpPurchasereturnentryDtos.get(i).getFUnit()+"'";
					List<Entity>  list= Db.use(DataSourceUtil.getDataSource()).query(sql);

					for (int j=0;j<list.size();j++)
					{
						if (list.get(j).get("f_fullname").toString().equals(erpPurchasereturnentryDtos.get(i).getFComunit().toString()))
						{
							comConverRate=new BigDecimal(list.get(j).get("F_ConvertRate").toString());
						}
						if (list.get(j).get("f_fullname").toString().equals(erpPurchasereturnentryDtos.get(i).getFBasicunit().toString()))
						{
							baseConverRate=new BigDecimal(list.get(j).get("F_ConvertRate").toString());
						}
					}
					//得到转换率之后开始转换
					//根据商品id和仓库id查询是否有此商品的库存数据
					String sql1="SELECT * FROM erp_inventory i where i.F_WarehouseId='"+erpPurchasereturnDto.getFWerahourseid()+ "' and i.F_GoodsId='"+erpPurchasereturnentryDtos.get(i).getFGoodsid()+"'";
					List<Entity> isInventory1=Db.use(DataSourceUtil.getDataSource()).query(sql1);
					ErpInventory erpInventory1=new ErpInventory();
					//本次退货数量
					BigDecimal retrurnQua=new BigDecimal(erpPurchasereturnentryDtos.get(i).getFReturnquantity());
					//修改数量=原有的数据+本次退货数量*转换率
					//如果有的话就修改对应商品的库存
					if (isInventory1.size()>0)
					{
						BigDecimal aftBasicQua=isInventory1.get(0).getBigDecimal("f_basicamount");
						BigDecimal aftComamQua=isInventory1.get(0).getBigDecimal("f_comamount");
						erpInventory1.setFId(isInventory1.get(0).get("f_id").toString());//根据id修改 一定呀加这句
						erpInventory1.setFGoodsid(erpPurchasereturnentryDtos.get(i).getFGoodsid());
						erpInventory1.setFWarehouseid(erpPurchasereturnDto.getFWerahourseid());
						erpInventory1.setFBasicamount(aftBasicQua.add(retrurnQua));
						erpInventory1.setFComamount(aftComamQua.add(retrurnQua));
						//是否需要转换 需要的话就重新赋值
						if (!erpPurchasereturnentryDtos.get(i).getFComunit().equals(erpPurchasereturnentryDtos.get(i).getFUnit()))
						{
							erpInventory1.setFComamount(aftComamQua.add(retrurnQua.multiply(comConverRate)));
						}
						else
						{
							erpInventory1.setFBasicamount(aftBasicQua.add(retrurnQua.multiply(baseConverRate)));
						}
						erpInventoryService.updateById(erpInventory1);
						erpPurchaseorderentry.setFId(erpPurchasereturnentryDtos.get(i).getFOrderentrtyid());
						erpPurchaseorderentry.setFOrderid(erpPurchasereturnDto.getFPurorderid());
						erpPurchaseorderentry.setFGoodsid(erpPurchasereturnentryDtos.get(i).getFGoodsid());
						//未入库数量=旧的未入库数量+退货数量
						erpPurchaseorderentry.setFNoReceiptQua(new BigDecimal(erpPurchasereturnentryDtos.get(i).getFNoReceiptQua()).add(new BigDecimal(erpPurchasereturnentryDtos.get(i).getFReturnquantity())).intValue());
						//已入库数量=旧的已入库数量-退货数量
						erpPurchaseorderentry.setFReceiptQua(new BigDecimal(erpPurchasereturnentryDtos.get(i).getFReceiptQua()).subtract(new BigDecimal(erpPurchasereturnentryDtos.get(i).getFReturnquantity())).intValue());
						erpPurchaseorderentryList.add(erpPurchaseorderentry);
						if(erpPurchaseorderentry.getFReceiptQua()==0)
						{
							statusList.add(status);
						}
					}
					else{
						return  false;
					}
				}
			}
		}
		//2.对采购订单的商品数量做修改（已入库数量、未入库数量）
		erpPurchaseorder.setFId(erpPurchasereturnDto.getFPurorderid());
		//只有所有的已入库数量都等于0，才修改为未入库，否则还是部分入库
		if (statusList.size()==erpPurchaseorderentryList.size())
		{
			erpPurchaseorder.setFStatus(1);
		}
		else
		{
			erpPurchaseorder.setFStatus(0);
		}
		erpPurchaseorderService.updateById(erpPurchaseorder);
		erpPurchaseorderentryService.updateBatchById(erpPurchaseorderentryList);

	     List<ErpPurchasereceiptentry>	erpPurchasereceiptentryList=new ArrayList<>();

		erpPurchasereturnentryDtos.forEach(erpPurchasereturnentryDto -> {
			erpPurchaseorderentryList.forEach(erpPurchaseorderentry -> {
				if (erpPurchaseorderentry.getFGoodsid() == erpPurchasereturnentryDto.getFGoodsid())
				{
					ErpPurchasereceiptentry erpPurchasereceiptentry=new ErpPurchasereceiptentry();
					erpPurchasereceiptentry.setFReceiptqua(erpPurchaseorderentry.getFReceiptQua());
					erpPurchasereceiptentry.setFNoreceiptqua(erpPurchaseorderentry.getFNoReceiptQua());
					erpPurchasereceiptentry.setFId(erpPurchasereturnentryDto.getFReceiptentryid());
					erpPurchasereceiptentryList.add(erpPurchasereceiptentry);
				}
			});
		});
		//修改入库单已入库和未入库数量
		erpPurchasereceiptentryService.updateBatchById(erpPurchasereceiptentryList);
		return true;
	}

	public List<ErpPurchasereturnentryVo> getErpPurchasereturnentryByParentId(String parentId){
		return erpPurchasereturnentryMapper.getList(parentId);
	}
}
